<template>
  <div>
    <!-- 客户授权License -->
    <el-dialog :title="config.titleLicense" :visible.sync="config.openLicense" width="1000px" height="100%" v-dialogDrag append-to-body>
      <el-form ref="formLicense" :model="formLicense" :rules="rulesLicense" :inline="true" label-width="160px">
        <!-- 操作工具栏 -->
        <el-row >
          <!-- <el-col :span="1.5">
            <el-button v-preventReClick type="primary" plain icon="el-icon-plus" size="mini" @click="handleAddLicense"
                      v-hasPermi="['hbcsupport:hbc-client-auth:create']">新增</el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-button v-preventReClick type="info" icon="el-icon-upload2" size="mini" @click="handleImportLicense"
                    v-hasPermi="['hbcsupport:hbc-client-auth:create']">导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-preventReClick type="warning" plain icon="el-icon-download" size="mini" @click="handleExportLicense" :loading="exportLoadingLicense"
                      v-hasPermi="['hbcsupport:hbc-client-auth:export']">导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearchLicense" @queryTable="getListLicense"></right-toolbar>
        </el-row>
        <el-row>
          <!-- 列表 -->
          <el-table v-loading="loadingLicense" :data="listLicense">
            <el-table-column label="编号" align="center" prop="id" />
            <!-- <el-table-column label="混合云客户授权管理id" align="center" prop="hbcClientAuthId" /> -->
            <el-table-column label="服务端私钥" align="center" prop="serverPrivateKey" :show-overflow-tooltip='true'/>
            <el-table-column label="服务端公钥" align="center" prop="serverPublicKey" :show-overflow-tooltip='true'/>
            <el-table-column label="客户端交换信息文件原文" align="center" prop="clientCsrData" >
              <!-- XXX TODO 内容太长时会闪烁，不显示内容 -->
              <template slot-scope="{ row }">
                <span v-if="row.clientCsrData && row.clientCsrData.length > 10">
                  <el-popover placement="top-start" title="文件原文" width="30" trigger="hover">
                    <div>{{ row.clientCsrData }}</div>
                      <span slot="reference">
                          {{ row.clientCsrData.substr(0, 10) + '...' }}
                      </span>
                  </el-popover>
                </span>
                <span v-else>{{ row.clientCsrData }}</span>
                <el-button v-preventReClick @click="handleDownloadData(row, 'clientCsrData')" >下载</el-button>
              </template>
            </el-table-column>
            <el-table-column label="客户端交换信息" align="center" prop="clientCsrInfo" >
              <template slot-scope="scope">
                <el-button v-preventReClick @click="handleViewJson(scope.row.clientCsrInfo)">查看</el-button>
              </template>
            </el-table-column>
            <el-table-column label="客户端公钥" align="center" prop="clientPublicKey" :show-overflow-tooltip='true'/>
            <el-table-column label="客户端license文件原文" align="center" prop="clientLicenseData" >
              <!-- XXX TODO 内容太长时会闪烁，不显示内容 -->
              <template slot-scope="{ row }">
                <span v-if="row.clientLicenseData && row.clientLicenseData.length > 10">
                  <el-popover placement="top-start" title="文件原文" width="30" trigger="hover">
                    <div>{{ row.clientLicenseData }}</div>
                      <span slot="reference">
                          {{ row.clientLicenseData.substr(0, 10) + '...' }}
                      </span>
                  </el-popover>
                </span>
                <span v-else>{{ row.clientLicenseData }}</span>
                <el-button v-preventReClick @click="handleDownloadData(row, 'clientLicenseData')" >下载</el-button>
              </template>
            </el-table-column>
            <el-table-column label="客户端license文件信息" align="center" prop="clientLicenseInfo" >
              <template slot-scope="scope">
                <el-button v-preventReClick @click="handleViewJson(scope.row.clientLicenseInfo)">查看</el-button>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" width="180">
              <template v-slot="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template v-slot="scope">
                <el-button v-preventReClick size="mini" type="text" icon="el-icon-view" @click="handleUpdateLicenseForm(scope.row)"
                          v-hasPermi="['hbcsupport:hbc-client-auth:update']">查看</el-button>
                <el-button v-preventReClick size="mini" type="text" icon="el-icon-delete" @click="handleDeleteLicenseForm(scope.row)"
                          v-hasPermi="['hbcsupport:hbc-client-auth:delete']">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页组件 -->
          <pagination v-show="totalLicense > 0"
            :total="totalLicense"
            :page.sync="config.queryParams.pageNo"
            :limit.sync="config.queryParams.pageSize"
            @pagination="getListLicense"/>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button v-preventReClick @click="cancelLicense">关闭</el-button>
      </div>
    </el-dialog>
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="titleLicenseForm" :visible.sync="openLicenseForm" width="500px" v-dialogDrag append-to-body>
      <el-form ref="formLicenseForm" :model="formLicenseForm" :rules="rulesLicenseForm" label-width="100px">
        <el-form-item label="混合云客户授权管理id" prop="hbcClientAuthId">
          <el-input v-model="formLicenseForm.hbcClientAuthId" placeholder="请输入混合云客户授权管理id" />
        </el-form-item>
        <el-form-item label="服务端私钥" prop="serverPrivateKey">
          <el-input v-model="formLicenseForm.serverPrivateKey" placeholder="请输入服务端私钥" type="textarea"/>
        </el-form-item>
        <el-form-item label="服务端公钥" prop="serverPublicKey">
          <el-input v-model="formLicenseForm.serverPublicKey" placeholder="请输入服务端公钥" type="textarea"/>
        </el-form-item>
        <el-form-item label="客户端交换信息文件原文" prop="clientCsrData">
          <el-input v-model="formLicenseForm.clientCsrData" placeholder="请输入客户端交换信息文件原文" type="textarea"/>
        </el-form-item>
        <el-form-item label="客户端交换信息" prop="clientCsrInfo">
          <el-input v-model="formLicenseForm.clientCsrInfo" placeholder="请输入客户端交换信息" type="textarea"/>
        </el-form-item>
        <el-form-item label="客户端公钥" prop="clientPublicKey">
          <el-input v-model="formLicenseForm.clientPublicKey" placeholder="请输入客户端公钥" type="textarea"/>
        </el-form-item>
        <el-form-item label="客户端license文件原文" prop="clientLicenseData">
          <el-input v-model="formLicenseForm.clientLicenseData" placeholder="请输入客户端license文件原文" type="textarea"/>
        </el-form-item>
        <el-form-item label="客户端license文件信息" prop="clientLicenseInfo">
          <el-input v-model="formLicenseForm.clientLicenseInfo" placeholder="请输入客户端license文件信息" type="textarea"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button v-preventReClick type="primary" @click="submitFormLicenseForm">确 定</el-button> -->
        <el-button v-preventReClick @click="cancelLicenseForm">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 导入客户端交换文件对话框 -->
    <el-dialog :title="uploadLicense.title" :visible.sync="uploadLicense.open" width="400px" append-to-body>
      <el-row>
        <el-col>
          <el-upload ref="uploadLicense" :limit="1" accept="*.*" :headers="uploadLicense.headers"
            :action="uploadLicense.url + '?hbcClientAuthId=' + uploadLicense.hbcClientAuthId" :disabled="uploadLicense.isUploading"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :on-error="handleFileError"
            :auto-upload="false" drag>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button v-preventReClick type="primary" @click="submitFileForm">确 定</el-button>
        <el-button v-preventReClick @click="uploadLicense.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 结束客户授权License -->
    <!-- json查看 -->
    <el-dialog title="JSON详细信息"
                 :visible.sync="showViewJsonDialog"
                 width="60%">
      <json-viewer :value="JSONData"
                    :expand-depth=5
                    copyable
                    boxed
                    sort></json-viewer>
    </el-dialog>
  </div>
</template>
<script>
import { createHbcClientAuthLicense, updateHbcClientAuthLicense, deleteHbcClientAuthLicense, getHbcClientAuthLicense, getHbcClientAuthLicensePage, exportHbcClientAuthLicenseExcel, downloadHbcClientAuthLicenseFileData } from "@/api/hbcsupport/hbcClientAuthLicense";

import {getBaseHeader} from "@/utils/request";

import JsonViewer from 'vue-json-viewer';

export default {
  props:{
    config:{
      hbcClientAuthId:undefined,
      titleLicense:"",
      openLicense: false,
      queryParams: {
        pageNo: 1,
        pageSize: 10
      },
    }
  },
  components: {
    JsonViewer,
  },
  data() {
    return {
      //=== 添加客户授权License
      formLicense:{
      },
      rulesLicense:{
      },

      // 遮罩层
      loadingLicense: true,
      exportLoadingLicense: false,
      downloadLoadingLicense: false,
      showSearchLicense: true,
      totalLicense: 0,
      listLicense: [],

      titleLicenseForm:"",
      openLicenseForm:false,
      formLicenseForm:{},
      rulesLicenseForm:{
      },

      // 导入参数
      uploadLicense: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        updateSupport: 0,
        // 设置上传的请求头部
        headers: getBaseHeader(),
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/admin-api/hbcsupport/hbc-client-auth-license/import-csr',
        hbcClientAuthId: 0
      },

      //===
      JSONData: {},
      showViewJsonDialog: false
    }
  },
  mounted() {
    // console.log("app-license-list:mounted");
  },
  methods: {
    //=== 客户授权License
    cancelLicense(){
      this.config.openLicense = false;
    },
    /** 查询列表 */
    getListLicense() {
      this.loadingLicense = true;
      // 执行查询
      getHbcClientAuthLicensePage(this.config.queryParams).then(response => {
        this.listLicense = response.data.list;
        this.totalLicense = response.data.total;
        this.loadingLicense = false;
      });
    },
     /** 表单重置 */
     resetLicenseForm() {
      this.formLicenseForm = {
        id: undefined,
        hbcClientAuthId: undefined,
        serverPrivateKey: undefined,
        serverPublicKey: undefined,
        clientCsrData: undefined,
        clientCsrInfo: undefined,
        clientPublicKey: undefined,
        clientLicenseData: undefined,
        clientLicenseInfo: undefined,
      };
      this.resetForm("formLicenseForm");
    },
    /** 新增按钮操作 */
    handleAddLicense() {
      this.resetLicenseForm();
      this.formLicenseForm.hbcClientAuthId=this.config.hbcClientAuthId;
      this.openLicenseForm = true;
      this.titleLicenseForm = "添加混合云支撑-混合云客户授权License";
    },
    handleUpdateLicenseForm(row) {
      this.resetLicenseForm();
      const id = row.id;
      getHbcClientAuthLicense(id).then(response => {
        this.formLicenseForm = response.data;
        this.openLicenseForm = true;
        this.titleLicenseForm = "修改混合云支撑-混合云客户授权License";
      });
    },
    submitFormLicenseForm(){
      this.$refs["formLicenseForm"].validate(valid => {
        if (!valid) {
          return;
        }
        // 修改的提交
        if (this.formLicenseForm.id != null) {
          updateHbcClientAuthLicense(this.formLicenseForm).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.openLicenseForm = false;
            this.getListLicense();
          });
          return;
        }
        // 添加的提交
        createHbcClientAuthLicense(this.formLicenseForm).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.openLicenseForm = false;
          this.getListLicense();
        });
      });
    },
    /** 删除按钮操作 */
    handleDeleteLicenseForm(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除混合云支撑-混合云客户授权License编号为"' + id + '"的数据项?').then(function() {
          return deleteHbcClientAuthLicense(id);
        }).then(() => {
          this.getListLicense();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExportLicense() {
      // 处理查询参数
      let params = {...this.config.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.$modal.confirm('是否确认导出所有混合云支撑-混合云客户授权License数据项?').then(() => {
          this.exportLoadingLicense = true;
          return exportHbcClientAuthLicenseExcel(params);
        }).then(response => {
          this.$download.excel(response, `混合云支撑-混合云客户授权License-${this.config.hbcClientAuthId}.xls`);
          this.exportLoadingLicense = false;
        }).catch(() => {});
    },
    cancelLicenseForm(){
      this.openLicenseForm = false;
      this.resetLicenseForm();
    },
    /** 导入按钮操作 */
    handleImportLicense() {
      this.uploadLicense.title = "导入客户端交互信息";
      this.uploadLicense.open = true;
      this.uploadLicense.hbcClientAuthId = this.config.hbcClientAuthId;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.uploadLicense.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      if (response.code !== 0) {
        this.$modal.msgError(response.msg);
        // XXX  TODO 可能是文件解析错误或者格式或者字段缺失等业务错误，这里跳过重传
        this.uploadLicense.open = false;
        this.uploadLicense.isUploading = false;
        this.$refs.uploadLicense.clearFiles();
        return;
      }
      this.getListLicense();
      this.uploadLicense.open = false;
      this.uploadLicense.isUploading = false;
      this.$refs.uploadLicense.clearFiles();
      // 拼接提示语
      let data = response.data;
      let text = '导入结果:'+JSON.stringify(response.data);
      this.$alert(text, "导入", { dangerouslyUseHTMLString: true });
    },
    handleFileError(error, file, fileList){
      this.$modal.msgError(error);
      // XXX TODO 正常的http错误
      this.uploadLicense.open = false;
      this.uploadLicense.isUploading = false;
      this.$refs.uploadLicense.clearFiles();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.uploadLicense.submit();
    },
    //=== 结束 客户授权License

    handleViewJson(jsonData) {
      this.showViewJsonDialog = true;
      new Promise(()=>{
        this.JSONData = JSON.parse(jsonData);
      }).then(
        //
      ).catch(()=>{
        this.JSONData = {};
      });

      //数据是string类型的需要用到JSON.parse(object)将string类型转换为JSON类型
      //row.jsonData的jsonData是后台接口数据所提供的，this.jsonData是容器，用来实现数据绑定显示的:value="jsonData"
    },
    handleDownloadData(row, field){
      let params = {field:field,id:row.id};
      this.$modal.confirm('是否确认导出数据?').then(() => {
          this.downloadLoadingLicense = true;
          return downloadHbcClientAuthLicenseFileData(params);
        }).then(response => {
          this.$download.download0(response, `License-${field}-${row.id}.txt`, "text/plain");
          this.downloadLoadingLicense = false;
        }).catch(() => {});
    }
  }
}
</script>

<style lang="scss" scoped>
/*json view 样式 */
::v-deep .el-dialog__body {
  padding: 0;
}
::v-deep .el-icon-close:before {
  color: black;
}
::v-deep .jv-container .jv-code.boxed {
  overflow-y: scroll;
  -webkit-overflow-scrolling: touch;
  overflow: -moz-scrollbars-none;
}
::v-deep .jv-container .jv-code.boxed::-webkit-scrollbar {
  display: none;
}
/*json view 样式 */

/*设置el-tooltip宽度*/
.el-tooltip__popper {
  max-width: 30px;
  line-height: 20px;
}
/*设置el-tooltip宽度*/
</style>
